articles

Home / DeveloperSection / Articles / Use jQuery toggleClass()

Use jQuery toggleClass()

Use jQuery toggleClass()

Anonymous User1840 17-Jan-2018

Introduction:

In this article we will explain what is toggleCLass() method in jQuery or how to add or remove class name from selected elements on clicking button in jQuery with example.

Description:

The jQuery toggleCLass() method is used to add or remove one or more classes from the html selected elements. This method toggles between adding and removing one or more class name. It checks each element for the specified class names. If the class name is already set, it removes and if the class name is not exists, it adds.

Example of jQuery toggleClass() method

<!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml'> <head>     <title>Jquery Tutorials</title>     <script src='Scripts/jquery-1.8.2.min.js'></script> </head> <body>     <script>         $(document).ready(function () {             $('button').click(function () {                 $('div').toggleClass('Myclass');             });         });     </script>             <div class='div'></div>         <div class='div'></div>     <button>Click here to add/remove class</button>     <style>         .div {             height: 100px;             width: 200px;             background: #77c4fe;             margin-bottom: 10px;                     }         .Myclass {             background: #f66262;         }     </style> </body> </html>

 

 

 

 

 

Output:

Use jQuery toggleClass()

 

When we click once on button “Myclass” class name adds in div and click once again “Myclass” class name removed fron div. like shown as below image:

Use jQuery toggleClass()

Also, Read  how to show tool tip in html using jquery


Updated 26-Dec-2022
I am a content writter !

Leave Comment

Comments

Liked By